package cn.dyw.engine.core.utils;

import cn.dyw.engine.core.exec.ReportResult;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 执行结果工具
 *
 * @author dyw770
 * @since 2021-08-03
 */
public final class DatabaseResultSetUtils {

    /**
     * 处理结果
     *
     * @param resultSet    查询结果
     * @param reportResult 报表结果
     */
    public static void handleResultSet(ResultSet resultSet, ReportResult reportResult)
            throws SQLException {

        List<String> schema = new ArrayList<>(16);
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnName(i);
            schema.add(columnName);
        }

        reportResult.initSchema(schema);

        Map<String, Object> data = null;
        while (resultSet.next()) {
            data = new HashMap<>(16);
            for (String columnName : schema) {
                Object value = resultSet.getObject(columnName);
                data.put(columnName, value);
            }
            reportResult.addData(data);
        }
    }
}
